<template>
  <div class="image-upload">
    <!-- action 必选参数，上传的地址   http-request: 覆盖默认的上传行为，可以自定义上传的实现   file-list用于回显图片属性  limit: 限制图片的上传数量-->
    <el-upload action="#" list-type="picture-card" :http-request="uploadFn" :file-list="fileList" :limit="limitImg" :class="{ disabled: fileList.length === limitImg }" :on-remove="removeFn">
      <i class="el-icon-plus" />
    </el-upload>
    <!-- <el-progress v-if="percentShow" :text-inside="true" :stroke-width="14" :percentage="percent" /> -->
  </div>
</template>

<script>
// var COS = require('cos-js-sdk-v5')
import COS from 'cos-js-sdk-v5'

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKID9B5rNgR0LRIvLWQ7aolodO0Y8WfXBaWC',
  SecretKey: 'YxA9uRtAl8HCrNefS2PaaXKxMWqztEKQ'
})
export default {
  props: {
    limitImg: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      fileList: [],
      percent: 0,
      percentShow: false
    }
  },
  methods: {
    uploadFn(file) {
      this.fileList.push({ url: '' })
      console.log(this.fileList)
      this.percentShow = true
      // 把图片上传到腾讯云
      cos.putObject(
        {
          Bucket: 'hr-project-75-1312454298' /* 必须  储存桶的名字*/,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: (Date.now()).toString()/* 必须  上传的文件名字  同时也是请求地址名字*/,
          StorageClass: 'STANDARD',
          Body: file.file, // 上传文件对象
          onProgress: (progressData) => {
            // console.log(JSON.stringify(progressData))
            // this.percent = progressData.percent * 100
          }
        },
        (err, data) => {
        //   console.log(err || data)
          if (err) return this.$message.error('图片上传错误，请重新上传！')
          this.fileList[this.fileList.length - 1].url = 'http://' + data.Location
          this.$emit('addEvent', this.fileList)
          // const timer = setTimeout(() => {
          //   this.percentShow = false
          //   clearTimeout(timer)
          // }, 1000)
        }
      )
    },
    removeFn(file, fileList) {
      this.fileList.splice(this.fileList.findIndex((item) => item.uid === file.uid), 1)
      // this.percent = 0
    }
  }
}
</script>

<style lang="scss">
.disabled {
  .el-upload--picture-card {
    display: none;
  }
}
.image-upload {
  display: inline-block;
  .el-progress {
    width: 100%;
  }
}
</style>
